package com.hzy.utils;

import java.net.InetAddress;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 这里填写描述
 * 填写修改说明
 *
 * @author hzy
 * @version Revision:v1.0
 * @since Date:2023-08-07 16:02
 */
public class UUIDUtils {

    private static String IP_ADDR;
    private static String PART_ID;
    private static final AtomicLong GEN_TIME_MILLIS = new AtomicLong(System.currentTimeMillis());
    private static final AtomicInteger SEQ_ID = new AtomicInteger(0);

    static {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            String host = inetAddress.getHostAddress();
            String[] addrArr = host.split("\\.");
            StringBuilder ipBuilder = new StringBuilder();
            for (String addr : addrArr) {
                ipBuilder.append(Long.toHexString(Long.parseLong(addr)));
            }
            IP_ADDR = ipBuilder.toString();
            PART_ID = Long.toHexString(System.currentTimeMillis());
            int half = (int) Math.ceil(PART_ID.length() / 2d);
            System.out.println("partId: " + PART_ID);
            PART_ID = PART_ID.substring(half, PART_ID.length());
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public static synchronized String generate() {
        long currentTimeMillis = System.currentTimeMillis();
        if (SEQ_ID.get() <= 0 && GEN_TIME_MILLIS.get() <= currentTimeMillis){
            while ( currentTimeMillis <= GEN_TIME_MILLIS.get() ){
                currentTimeMillis = System.currentTimeMillis();
            }
            GEN_TIME_MILLIS.set(currentTimeMillis);
        }
        if ( currentTimeMillis > GEN_TIME_MILLIS.get() ){
            GEN_TIME_MILLIS.set(currentTimeMillis);
            SEQ_ID.set(0);
        }
        String temp = Long.toHexString(GEN_TIME_MILLIS.get())
                + "-"
                + IP_ADDR
                + "-"
                + PART_ID
                + "-"
                + Integer.toHexString(SEQ_ID.incrementAndGet());
        return temp;
    }

    public static void main(String[] args) throws Exception {
        /*Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                for (int j = 0; j < 10000; j++) {
                    String uuid = UUIDUtils.generate();
                    System.out.println(uuid);
                    if (!map.containsKey(uuid)){
                        map.put(uuid, uuid);
                    } else {
                        System.err.println(uuid);
                    }
                }
            }).start();
        }
        Thread.sleep(5000);*/

        long currentTimeMillis = System.currentTimeMillis();
        // 185768167a5  1675f
        System.out.println(currentTimeMillis);
        System.out.println(665096 / 1000 / 60);
    }

}
